package com.yang.service;

import com.yang.dao.AddressDao;
import com.yang.dao.AdsDao;
import com.yang.dao.ProductDao;
import com.yang.entity.Address;
import com.yang.entity.Product;
import com.yang.entity.Productcar;
import com.yang.dao.ProductcarDao;
import com.yang.util.RespEntity;

import java.util.*;

public class ProductcarService {
     ProductcarDao productcarDao = new ProductcarDao();
     AddressDao addressDao = new AddressDao();
    ProductDao productDao = new ProductDao();
    public RespEntity addProductcar(Integer pid , Integer uid , Integer count) {
        //根据id查询商品
        Product product = productcarDao.queryProductcarBySql("select * from product where id=" + pid).get(0);
      /*  System.out.println("根据sql语句查询商品："+product);*/

        //封装成购物车对象
        Productcar productcar=new Productcar(product,uid,count);
        //查询购物车是否有商品
        Productcar car = productcarDao.queryProductcarPidUid(pid, uid);

        //判断购物车里面有没有
        int sum=0;
        if(null==car){
            //表示不存在，直接添加
            sum= productcarDao.saveProductcar(productcar);
        }else{
            //表示存在修改购买的数量
            count=car.getNum()+count;
            sum= productcarDao.updateProductCartNumber(car.getId(),count);
        }
        return new RespEntity(2000,"添加购物车",sum);
    }
    //根据用户id查询他的商品
    public RespEntity queryProductCaeByUid(Integer uid){
        List<Productcar> productcars = productcarDao.queryByUid(uid);
        return new RespEntity(200,"查询成功",productcars);
    }
    //删除
    public RespEntity deleteProductcar(Integer id){
        int num = productcarDao.deleteProductcar(id);
        return new RespEntity(200,"删除",num);
    }
    //下订单
    public RespEntity shopping(String[] pids,String addrId){
        //查询出购物车中的商品
        String sql="select * from productcar where id in (";
        for (int i = 0; i < pids.length; i++) {
            sql=sql+pids[i];
            if(i<pids.length-1){
                sql=sql+",";
            }
        }
        sql=sql+")";
        System.out.println(sql);
        //你要购买的商品
        List<Productcar> productcars = productcarDao.queryProductcarsBySql(sql);
        //判断库存够不够
        String productName=null;
        for (Productcar productcar : productcars) {
            Product product = productDao.queryById(productcar.getPid());
            if(product.getStock()<productcar.getNum()){
                productName=product.getName();
                break;
            }
        }
        //当库存不够，返回
        if(null!=productName){
            return new RespEntity(500,"库存不够！",productName);
        }
        //查询出发货地址
        Address address = addressDao.queryAddressById(Integer.parseInt(addrId));
        //开始下订单
        int num = productcarDao.goBuyShopping(productcars, address);

        return new RespEntity(200,"下单成功",num);
    }
}

